package com.nanjing.east.cloud.notify;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.nanjing.east.cloud.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Controller
@Slf4j
public class PageAuthNotice {

    @Value("${alipay.appid:''}")
    private String alipayAppId;

    @Value("${alipay.pub.key:''}")
    private String alipayPubKey;

    @Value("${app.private.key:''}")
    private String appPrivateKey;


    @Value("${wechat.appid:''}")
    private String wechatAppId;

    @Value("${wechat.secret:''}")
    private String wechatSecret;


    //支付宝网页授权二维码url:https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2018112662315802&scope=auth_base&state=1000001&redirect_uri=http://47.107.255.155:8080/alipay_notify

    @RequestMapping("/alipay_notify")
    @ResponseBody
    ResponseVO<String> alipay_notify(HttpServletRequest request) {
        Map<String, String> params = convertRequestParamsToMap(request); // 将异步通知中收到的待验证所有参数都存放到map中
        String paramsJson = JSON.toJSONString(params);
        log.info("支付宝回调：{}", paramsJson);

        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", alipayAppId, appPrivateKey, "json", "UTF-8", alipayPubKey, "RSA2");
        AlipaySystemOauthTokenRequest request1 = new AlipaySystemOauthTokenRequest();
        request1.setCode(params.get("auth_code"));
        request1.setGrantType("authorization_code");
        try {
            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request1);
            String alipayUserId = oauthTokenResponse.getAlipayUserId();
            String accessToken = oauthTokenResponse.getAccessToken();
            log.info("获取到用户编号:{},访问令牌:{}", alipayUserId, accessToken);
        } catch (AlipayApiException e) {
            //处理异常
            //e.printStackTrace();
        }
        return null;
    }



    //微信网页授权二维码url:https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=http://47.107.255.155:8080/wechat_notify&response_type=code&scope=snsapi_base&state=123#wechat_redirect
    @RequestMapping("/wechat_notify")
    @ResponseBody
    ResponseVO<String> wechat_notify(HttpServletRequest request) {
        Map<String, String> params = convertRequestParamsToMap(request); // 将异步通知中收到的待验证所有参数都存放到map中
        String paramsJson = JSON.toJSONString(params);
        log.info("微信回调：{}", paramsJson);

        String result = httpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wechatAppId + "&secret=" + wechatSecret + "&code=" + params.get("code") + "&grant_type=authorization_code");

        log.info("获取到用户信息:{}",result);
        return null;
    }


   /* public static void main(String[] args) {
        System.out.println(httpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+"wx51eb30e53f890ec0"+"&secret="+"dfcbg20181029dfcbg20181029dfcbg2"+"&code="+"CODE"+"&grant_type=authorization_code"));
    }*/


    private static String httpGet(String url) {
        CloseableHttpClient httpCilent2 = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)   //设置连接超时时间
                .setConnectionRequestTimeout(5000) // 设置请求超时时间
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)//默认允许自动重定向
                .build();
        HttpGet httpGet2 = new HttpGet(url);
        httpGet2.setConfig(requestConfig);
        String srtResult = "";
        try {
            HttpResponse httpResponse = httpCilent2.execute(httpGet2);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                srtResult = EntityUtils.toString(httpResponse.getEntity());//获得返回的结果
                return srtResult;
            } else if (httpResponse.getStatusLine().getStatusCode() == 400) {
                //..........
            } else if (httpResponse.getStatusLine().getStatusCode() == 500) {
                //.............
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpCilent2.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }
}
